package com.aizuda.boot.modules.third.openApi;

import com.aizuda.boot.modules.business.contract.dto.SingleResponse;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yangshen
 * @version 1.0
 * @date 2025/6/19
 */
@RestController
@RequestMapping("/open/bank")
@Tag(name= "银行API接口")
@Slf4j
public class BankApiController {

    @Value("${alicloud.appcode}")
    private String appcode;

    @Value("${alicloud.apis.bank.host}")
    private String host;

    @Value("${alicloud.apis.bank.path}")
    private String path;

    private final OkHttpClient httpClient;

    public BankApiController() {
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    @Operation(summary = "根据关键词模糊查询银行网点信息")
    @GetMapping("/query")
    public SingleResponse<Map<String, Object>> queryBankBranch(
            @Parameter(description = "查询关键词", required = true)
            @RequestParam String keyword) {
        
        try {
            // 构建请求URL，对keyword进行URL编码
            String encodedKeyword = URLEncoder.encode(keyword, StandardCharsets.UTF_8);
            String url = host + path + "?keyword=" + encodedKeyword;

            // 构建请求
            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Authorization", "APPCODE " + appcode)
                    .get()
                    .build();
            
            // 发送请求
            try (Response response = httpClient.newCall(request).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    String responseBody = response.body().string();
                    log.info("银行网点查询成功，关键词: {}", keyword);
                    
                    try {
                        // 将JSON字符串解析为Map
                        Map<String, Object> resultMap = JSONObject.parseObject(responseBody, Map.class);
                        return SingleResponse.of(resultMap);
                    } catch (Exception parseException) {
                        log.error("JSON解析失败，关键词: {}, 响应内容: {}, 错误信息: {}", 
                                keyword, responseBody, parseException.getMessage());
                        return SingleResponse.failure(500, "响应数据解析失败");
                    }
                } else {
                    log.error("银行网点查询失败，HTTP状态码: {}, 关键词: {}", response.code(), keyword);
                    return SingleResponse.failure(500, "银行网点查询失败");
                }
            }
        } catch (IOException e) {
            log.error("银行网点查询异常，关键词: {}, 错误信息: {}", keyword, e.getMessage(), e);
            return SingleResponse.failure(500, "网络请求异常: " + e.getMessage());
        } catch (Exception e) {
            log.error("银行网点查询未知异常，关键词: {}, 错误信息: {}", keyword, e.getMessage(), e);
            return SingleResponse.failure(500, "系统异常: " + e.getMessage());
        }
    }
}
